package com.cyzy.filter;

import com.alibaba.fastjson.JSON;
import com.cyzy.dto.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.filter.OrderedFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;

import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;


@Component
public class AuthFilter implements GlobalFilter, Ordered {
    @Autowired
    private RedisTemplate<String,Object> redisTemplate;
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //1.白名单;
        String url = request.getURI().getPath();
        String[] whilteList={"/login","/register","/getCode","resetToken"};
        for(String white:whilteList){
            if(url.contains(white)){
                return chain.filter(exchange);  //这里放过，走下一个过滤器   设计模式：过滤器设计模式（链式设计模式）
            }
        }
        //2.是否携带token
//        List<String> lists=request.getHeaders().get("token");
//        if(lists==null || lists.size()<=0){
//            //没有token
//            return getNoAuth(response,"没有token");
//        }
        // 2. 是否携带 token (Authorization: Bearer <token>)
        List<String> lists = request.getHeaders().get(HttpHeaders.AUTHORIZATION);
        if (lists == null || lists.isEmpty()) {
            // 没有 token
            return getNoAuth(response, "没有token");
        }
        String token = lists.get(0);
        System.out.println("token:"+token);
        //3.判断token是否有效
        boolean re = redisTemplate.hasKey(token);
        System.out.println("re:"+re);
        if(!re){
            //无效的token
            return getNoAuth(response,"无效的token");
        }
        //4.权限是否足够   siro 或 spring security
        return chain.filter(exchange);  //这里放过，走下一个过滤器   设计模式：过滤器设计模式（链式设计模式）
    }
    public Mono<Void>  getNoAuth(ServerHttpResponse response,String msg){
        //没有token  友好提示   Result  code=401 message
        R result = R.ok().code(401).message(msg);
        String json = JSON.toJSONString(result);

        response.setStatusCode(HttpStatus.UNAUTHORIZED);  //默认200  401表示没有权限或授权
        response.getHeaders().add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
        DataBuffer dataBuffer = response.bufferFactory().wrap(json.getBytes());
        return response.writeWith(Mono.just(dataBuffer));
    }

    @Override
    public int getOrder() {
        return 1;  //多个过滤器的过滤顺序
    }


}